package consul

import (
	"encoding/gob"
	"os"
	"sync"
)

type Cache struct {
	kv sync.Map
}

func newCache() *Cache {
	return &Cache{
		kv: sync.Map{},
	}
}

func (c *Cache) dumpFile(name string) (err error) {
	dumps := c.dump()
	var f *os.File
	if f, err = os.OpenFile(name, os.O_RDWR|os.O_TRUNC|os.O_CREATE, 0755); err != nil {
		return
	}
	return gob.NewEncoder(f).Encode(&dumps)
}

func (c *Cache) loadFile(name string) (err error) {
	var f *os.File
	var dumps map[string]string
	if f, err = os.OpenFile(name, os.O_RDONLY, 0755); err != nil {
		return
	}
	if err = gob.NewDecoder(f).Decode(&dumps); err != nil {
		return
	}
	for k, v := range dumps {
		c.kv.Store(k, v)
	}
	return
}

func (c *Cache) dump() map[string]string {
	var ret = make(map[string]string)
	c.kv.Range(func(key, value interface{}) bool {
		k, _ := key.(string)
		v, _ := value.(string)
		ret[k] = v
		return true
	})

	return ret
}
